var LocalStrategy    = require('passport-local').Strategy;

module.exports = function(passport, db, authUtil) {
    var collection = db.collection('users');
    // =========================================================================
    // passport session setup ==================================================
    // =========================================================================
    // required for persistent login sessions
    // passport needs ability to serialize and unserialize users out of session

    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user);
    });

    // used to deserialize the user
    passport.deserializeUser(function(user, done) {
        collection.findOne({"email": user.email}, function(err, result) {
            done(err, user);
        });
    });

    // =========================================================================
    // LOCAL LOGIN =============================================================
    // =========================================================================
    passport.use('local-login', new LocalStrategy({
        // by default, local strategy uses email and password, we will override with email
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
    },
    function(req, email, password, done) {
        if (email){
            email = email.toLowerCase(); // Use lower-case e-mails to avoid case-sensitive e-mail matching
        }
        // asynchronous
        process.nextTick(function() {
            collection.findOne({ "email" :  email }, function(err, user) {
                // if there are any errors, return the error
                if (err){
                    return done(err);
                }

                // if no user is found, return the message
                if (!user){
                    return done(null, false, req.flash('loginMessage', 'No user found.'));
                }

                if (!authUtil.compareHashedPassword(password, user.password)){
                    return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
                }

                // all is well, return user
                return done(null, user);
            });
        });

    }));

    // =========================================================================
    // LOCAL SIGNUP ============================================================
    // =========================================================================
    passport.use('local-signup', new LocalStrategy({
        // by default, local strategy uses email and password, we will override with email
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) {
        process.nextTick(function() {
            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            collection.findOne({'email' :  email }, function(err, user) {
                if (err)
                    return done(err);
                if (user) {
                    return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
                } else {
                    // if there is no user with that email --> create the user
                    var newUser = {
                        "email": email,
                        "password": authUtil.generateHash(password),
                        "role": "ADMIN"
                    };
                    collection.insert([
                        {
                            "email": newUser.email,
                            "password": newUser.password,
                            "role": newUser.role,
                            "createdDate": new Date()
                        }
                    ], function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }
            });
        });
    }));
};
